package com.ruoyi.common.wx.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.app.JwtTokenUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.wx.domain.WxUser;
import com.ruoyi.common.wx.domain.vo.WxUserRegisterVo;
import com.ruoyi.common.wx.mapper.WxUserMapper;
import com.ruoyi.common.wx.service.IWxUserService;
import com.ruoyi.common.wx.service.IWxUserTokenService;
import com.ruoyi.common.wx.service.IWxService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements IWxUserService {
    public static void main(String[] args) {
        System.out.println(SecurityUtils.encryptPassword("ay3@345"));
    }
    @Autowired
    IWxService wxService;
    @Autowired
    IWxUserTokenService wxUserTokenService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Resource
    WxUserMapper wxUserMapper;

    @Override
    public AjaxResult loginByOpenId(String openId) throws IOException {
        JSONObject json = new JSONObject();
        json.put("openid", openId);
        /** 获取token */
        WxUser wxUser = this.query().eq("open_id", openId).one();
        String token = "";
        if (wxUser == null) {
            return AjaxResult.error("用户不存在");
        } else {
            Map<String, Object> claims = new HashMap<>();
            claims.put("appUserId", wxUser.getId());
            claims.put("appUser", wxUser);
            token = jwtTokenUtil.createToken(String.valueOf(wxUser.getId()), claims);
            json.put("phone", wxUser.getPhone());
        }
        WxUser wxUser1 = this.query().eq("open_id", openId).one();
        json.put("user", wxUser1);
        json.put("token", token);
        return AjaxResult.success(json);
    }

    @Override
    public AjaxResult getUserInfo(String token) throws IOException {
        if (!jwtTokenUtil.validateToken(token)) {
            return AjaxResult.error("token无效");
        }
        Map<String, Object> claims = jwtTokenUtil.parseToken(token);
        return AjaxResult.success(claims);
    }

    @Override
    public JSONObject loginOrRegisterByOpenId(String jsCode) throws IOException {

        JSONObject sessionKeyJson = JSONObject.parseObject(wxService.getSessionKey(jsCode));

        if (sessionKeyJson.containsKey("session_key") && StringUtils.isNotEmpty(sessionKeyJson.getString("session_key"))) {
            String openId = sessionKeyJson.getString("openid");
            JSONObject json = new JSONObject();
            json.put("openid", openId);
            /** 获取token */
            Assert.hasLength(openId, "缺少微信信息！");
            WxUser wxUser = this.query().eq("open_id", openId).one();
            String token = "";
            if (wxUser == null) {
                WxUser wxUserNew = new WxUser();
                wxUserNew.setOpenId(openId);
                wxUserNew.setCreateTime(new Date());
                this.save(wxUserNew);
                token = wxUserTokenService.createToken(wxUserNew.getId());
            } else {
                token = wxUserTokenService.createToken(wxUser.getId());
                json.put("phone", wxUser.getPhone());
            }
            WxUser wxUser1 = this.query().eq("open_id", openId).one();
            json.put("user", wxUser1);
            json.put("token", token);
            return json;
        } else {
            throw new RuntimeException("session_key获取失败！");
        }
    }

    /**
     * 根据主键删除记录
     *
     * @return
     */
    @Override
    @Transactional
    public AjaxResult removeWxUserByTableId(Long[] ids) {
        // 删除主表信息
        this.removeByIds(Arrays.asList(ids));
//        this.removeById(id);
        return AjaxResult.success("删除成功！！");
    }

    /**
     * 根据条件分页查询
     *
     * @return
     */
    @Override
    public Page<WxUser> queyPageByCondition(WxUser wxUser, Page<WxUser> page) {
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(wxUser.getName()), "name", wxUser.getName());
        queryWrapper.like(StringUtils.isNotBlank(wxUser.getPhone()), "phone", wxUser.getPhone());
        queryWrapper.like(StringUtils.isNotBlank(wxUser.getCompany()), "company", wxUser.getCompany());
        queryWrapper.orderByDesc("create_time");
        // 构造复杂查询
        return wxUserMapper.selectPage(page, queryWrapper);
    }

    @Override
    public String getWxPhone(WxUserRegisterVo input) throws IOException {
        Assert.hasLength(input.getOpenid(), "缺少微信信息！");
        Assert.hasLength(input.getCode(), "缺少授权信息！");
        /** 解密获取手机号码 */
        String phone = wxService.getUserPhonenumber(input.getCode());
        //更新微信用户手机号
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("open_id", input.getOpenid());
        WxUser wxUser = new WxUser();
        wxUser.setPhone(phone);
        wxUserMapper.update(wxUser, queryWrapper);
        return phone;
    }

    @Override
    public String loginOrRegister(WxUserRegisterVo input) throws IOException {
        Assert.hasLength(input.getOpenid(), "缺少微信信息！");
        Assert.hasLength(input.getCode(), "缺少授权信息！");

        /** 解密获取手机号码 */
        String userPhonenumber = wxService.getUserPhonenumber(input.getCode());
        //根据电话号码来查询
        List<WxUser> wxUser = query().eq("phone", userPhonenumber).list();
        if (CollectionUtils.isEmpty(wxUser)) {
//            return Constants.USER_NOT_EXIST;
            return register(new WxUser()
                    .setAvatarUrl(input.getAvatarUrl())
                    .setPhone(userPhonenumber)
                    .setUserType(Constants.USER_TYPE_2)
                    .setOpenId(input.getOpenid()));
        } else {
            WxUser wxUser1 = wxUser.get(0);
            if (StringUtils.isBlank(wxUser1.getOpenId())) {
                wxUser1.setOpenId(input.getOpenid());
                wxUserMapper.updateById(wxUser1);
            }
            /** 获取token */
            return wxUserTokenService.createToken(wxUser1.getId());
        }
    }

    @Override
    public WxUser getByOpenId(String openId) {
        return query().eq("open_id", openId).one();
    }

    @Override
    public String register(WxUser input) {
        List<WxUser> user = query().eq("phone", input.getPhone()).list();
        if (!CollectionUtils.isEmpty(user)) throw new RuntimeException("用户号码已存在！");
        if (!save(input)) throw new RuntimeException("新增失败！");

        /** 获取token */
        return wxUserTokenService.createToken(input.getId());
    }

    @Override
    public String checkEmpower(String openId) {
        Assert.hasLength(openId, "缺少微信信息！");
        WxUser wxUser = query().eq("open_id", openId).one();
        if (wxUser == null || StringUtils.isEmpty(wxUser.getPhone())) return null;
        return wxUserTokenService.createToken(wxUser.getId());
    }


}
